//
//  BDMyOrderViewController.m
//  iOS_beboy
//
//  Created by wen on 2017/9/19.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDMyOrderViewController.h"
#import "BDUserModel.h"
#import "BDMyOrderCell.h"
#import "BDMyOrderDetailViewController.h"
#import "BDMyCouponsDetailViewController.h"
#import "GoodsDetailsViewController.h"
#import <WXApi.h>
#import <AlipaySDK/AlipaySDK.h>
#import "AppDelegate.h"
#import "BDHomeDetailViewController.h"

@interface BDMyOrderViewController ()<UITableViewDelegate, UITableViewDataSource, BDMyOrderCellDelegate>
{
    NSInteger currentSelectedIndex;
}
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *topView;

@end

@implementation BDMyOrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.title = ASLocalizedString(@"我的订单");
    
    _datasource = [NSMutableArray array];
    [self requestDatasource];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}

- (void)requestDatasource{
    [MBManager showLoadingAlert:ASLocalizedString(@"请稍后")clickHidden:NO clickBlock:nil];
    
//    NSString *url = [NSString stringWithFormat:@"%@payment/orders?page=%@&size=%@", KBDBaseURL, self.startPage, self.pageSize];
    NSString *url = [NSString stringWithFormat:@"%@payment/orders", KBDBaseURL];
    NSMutableDictionary *para = @{@"page":self.startPage,
                                  @"size":self.pageSize}.mutableCopy;
    
    
    NSArray *statusArray = @[[NSString stringWithFormat:@"%@", @(BDMyOrderStatusWaitPay)],
                             [NSString stringWithFormat:@"%@", @(BDMyOrderStatusPaySuccessed)],
                             [NSString stringWithFormat:@"%@", @(BDMyOrderStatusApplyRefund)],
                             [NSString stringWithFormat:@"%@", @(BDMyOrderStatusPayBack)]];
    [para setObject:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:statusArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] forKey:@"status"];
    
    NSArray *typeArray = nil;
    switch (currentSelectedIndex) {
        case 0:
            //全部
            typeArray = @[[NSString stringWithFormat:@"%@", @(BDMyOrderTypePost)],
                          [NSString stringWithFormat:@"%@", @(BDMyOrderTypeProduct)],
                          [NSString stringWithFormat:@"%@", @(BDMyOrderTypeShopCoupon)]];
            break;
        case 1:
            //帖子
            typeArray = @[[NSString stringWithFormat:@"%@", @(BDMyOrderTypePost)]];
            break;
        case 2:
            //套餐
            typeArray = @[[NSString stringWithFormat:@"%@", @(BDMyOrderTypeShopCoupon)]];
            break;
        case 3:
            //商品
            typeArray = @[[NSString stringWithFormat:@"%@", @(BDMyOrderTypeProduct)]];
            break;
        default:
            break;
    }
    if (typeArray) {
        [para setObject:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:typeArray options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding] forKey:@"type"];
    }
    
    NSString *headValid = [BDUserModel getHeaderValidation];
    RACSignal *signal = [[BDNetworkingServer v2_GET:url parameters:para validation:headValid automaticProcessingError:YES] execute:nil];
    [signal subscribeNext:^(id  _Nullable x) {
        [MBManager hideAlert];
        
        if ([self.tableView.mj_header isRefreshing]) {
            [self.datasource removeAllObjects];
            [self.tableView.mj_header endRefreshing];
        }
        
        [self.tableView.mj_footer endRefreshing];
        
        NSArray *resultArray = [BDMyOrderModel mj_objectArrayWithKeyValuesArray:x[@"list"]];
        for (int i = 0; i < resultArray.count; i++) {
            BDMyOrderLayout *layout = [[BDMyOrderLayout alloc] initWithOrder:resultArray[i]];
            [self.datasource addObject:layout];
        }

        self.startPage = x[@"next_page"];
        self.isEnd = [x[@"is_end"] boolValue];
        [self.tableView reloadData];
        
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.startPage = @"1";
            [self requestDatasource];
        }];
        self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [self requestDatasource];
        }];
        
        [self setReservationTableiewFooterViewStateFor:self.tableView datasourceCount:self.datasource.count];
    }];
    [signal subscribeError:^(NSError * _Nullable error) {
        [MBManager hideAlert];
        if (self.datasource.count == 0) {
            [self showErrorViewWithTapBlock:^{
                [self requestDatasource];
            }];
        }
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _datasource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"orderCell";
    BDMyOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];
    cell.delegate = self;
    BDMyOrderLayout *layout = _datasource[indexPath.row];
    [cell setLayout:layout];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return ((BDMyOrderLayout *)_datasource[indexPath.row]).height;
}

- (void)cellDidClick:(BDMyOrderCell *)cell {
    BDMyOrderLayout *layout = cell.orderView.layout;
    switch (layout.order.type) {
        case BDMyOrderTypePost:{
            BDHomeDetailViewController *homeDetailVC = [[BDHomeDetailViewController alloc] init];
            homeDetailVC.post_id = layout.order.object_id;
            [self.navigationController pushViewController:homeDetailVC animated:YES];
        }break;
        case BDMyOrderTypeProduct:{
            
        }break;
        case BDMyOrderTypeShopCoupon:{
            NSString *productName = nil;
            if (layout.order.object) {
                productName = layout.order.object[@"title"];
            }
            if ([productName isNotBlank] == NO) {
                [MBManager showBriefAlert:ASLocalizedString(@"该套餐不存在，无法查看")clickHidden:NO clickBlock:nil];
                return;
            }
            BDMyOrderDetailViewController *detailOrderVc = [[BDMyOrderDetailViewController alloc] init];
            detailOrderVc.model = layout;
            [self.navigationController pushViewController:detailOrderVc animated:YES];
        }break;
        default:
            break;
    }
}

- (void)cellDidClickButton:(BDMyOrderCell *)cell {
    BDMyOrderLayout *layout = cell.orderView.layout;
    if (layout.order.status == BDMyOrderStatusWaitPay) {
        //跳转付款
        AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
        appDelegate.payResultBlock = ^(int state) {
            if (state == 1) {
                //这里刷新页面
                [_tableView.mj_header beginRefreshing];
            }else if (state == 2) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付发生错误")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            }else if (state == 3) {
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付取消")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
            }
        };
        if (layout.order.channel == 0) {
            [self aliPayWithPara:layout];
        }else if (layout.order.channel == 1) {
            [self wxPayWithPara:layout];
        }
    }else{
        switch (layout.order.type) {
            case BDMyOrderTypePost:
                //跳到阅读详情
                
                break;
            case BDMyOrderTypeProduct:{
                //跳到商品详情
                //            GoodsDetailsViewController *goodsDetailVC = [[GoodsDetailsViewController alloc] init];
                //            BDMallProductModel *productModel = [[BDMallProductModel alloc] init];
                //            productModel.product_id = [layout.order.object[@"id"] integerValue];
                
            }break;
            case BDMyOrderTypeShopCoupon:{
                NSString *productName = nil;
                if (layout.order.object) {
                    productName = layout.order.object[@"title"];
                }
                if ([productName isNotBlank] == NO) {
                    [MBManager showBriefAlert:ASLocalizedString(@"该套餐不存在，无法查看")clickHidden:NO clickBlock:nil];
                    return;
                }
                //跳到套餐详情
                BDMyCouponsDetailViewController *couponsDetailVC = [[BDMyCouponsDetailViewController alloc] init];
                couponsDetailVC.code = layout.order.object[@"code"];
                [self.navigationController pushViewController:couponsDetailVC animated:YES];
            }break;
            default:
                break;
        }
    }
}

- (void)aliPayWithPara:(BDMyOrderLayout *)layout{
    NSString *appScheme = @"beBoyAliPay";
    [[AlipaySDK defaultService] payOrder:layout.order.payment_info fromScheme:appScheme callback:^(NSDictionary *resultDic) {
        NSInteger stateCode = [resultDic[@"resultStatus"] integerValue];
        if (stateCode == 9000) {
            //这里刷新页面
            [_tableView.mj_header beginRefreshing];
            
        }else if (stateCode == 4000) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付发生错误")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
        }else if (stateCode == 6001) {
            [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"支付取消")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];
        }
    }];
}

- (void)wxPayWithPara:(BDMyOrderLayout *)layout{
    
    NSData *jsonData = [layout.order.payment_info dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *x = [NSJSONSerialization JSONObjectWithData:jsonData
                                                      options:NSJSONReadingMutableContainers
                                                        error:&err];
    
    PayReq *request = [[PayReq alloc] init];
    request.openID = x[@"app_id"];
    request.partnerId = x[@"merchant_id"];
    request.prepayId = x[@"prepay_id"];
    request.package = @"Sign=WXPay";
    request.nonceStr= x[@"nonce_str"];
    request.timeStamp= (UInt32)[x[@"timestamp"] integerValue];
    request.sign= x[@"sign"];
    [WXApi sendReq:request];
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, self.topView.bottom, kBDScreenWidth, kBDScreenHeight - self.topView.bottom) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[BDMyOrderCell class] forCellReuseIdentifier:@"orderCell"];
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)topView{
    if (!_topView) {
        self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, 45)];
        [self.view addSubview:_topView];
        
        UIView *head = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 45)];
        head.backgroundColor = kBDColorGray;
        head.bottom = _topView.height;
        [_topView addSubview:head];
        
        UIView *contenView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 40)];
        contenView.backgroundColor = [UIColor whiteColor];
        [head addSubview:contenView];
        
        NSArray *buttArr = @[ASLocalizedString(@"全部"),ASLocalizedString(@"帖子"),ASLocalizedString(@"套餐"), ASLocalizedString(@"商品")];
        CGFloat buttonWidth = 70;
        CGFloat space = (kBDScreenWidth - buttonWidth * buttArr.count) / (buttArr.count + 1);
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(space, 0, buttonWidth, 1.5)];
        lineView.backgroundColor = KBDColorBlue;
        lineView.bottom = contenView.height;
        [contenView addSubview:lineView];
        
        for (int i = 0; i < buttArr.count; i++) {
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.frame = CGRectMake(space + (space + buttonWidth)*i, 0, buttonWidth, 40);
            [button setTitle:buttArr[i] forState:UIControlStateNormal];
            [button setTitleColor:[UIColor colorWithHexString:@"#1c1c1c"] forState:UIControlStateNormal];
            [button setTitleColor:KBDColorBlue forState:UIControlStateSelected];
            button.titleLabel.font = [UIFont systemFontOfSize:14];
            button.tag = 1415 + i;
            [contenView addSubview:button];
            if (i == 0) {
                button.selected = YES;
                currentSelectedIndex = i;
            }
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if ( i == currentSelectedIndex) {
                    // BDLog(ASLocalizedString(@"点击了相同的按钮"));
                    return;
                }
                UIButton *oldButton = [contenView viewWithTag:1415 + currentSelectedIndex];
                oldButton.selected  = NO;
                
                [UIView animateWithDuration:0.3 animations:^{
                    lineView.centerX = button.centerX;
                } completion:^(BOOL finished) {
                    button.selected = YES;
                    currentSelectedIndex = i;
                    [self.datasource removeAllObjects];
                    self.startPage = @"1";
                    [self requestDatasource];
                }];
            }];
        }
    }
    return _topView;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
